package xin.marcher.module.search.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.constants.RocketDelayedLevel;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.search.domain.dto.TableDataChangeDTO;
import xin.marcher.module.search.message.MessageHandlerManager;
import xin.marcher.module.search.mq.producer.DefaultProducer;

import java.util.List;
import java.util.Objects;

/**
 * 搜索模块在商品变更的时候更新商品索引
 */
@Slf4j
@Component
public class ProductUpdateListener implements MessageListenerConcurrently {

    @Autowired
    private MessageHandlerManager messageHandlerManager;

    @Autowired
    private DefaultProducer defaultProducer;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("执行商品索引数据更新逻辑，消息内容：{}", msg);

                TableDataChangeDTO tableDataChangeDTO = JsonUtil.json2Object(msg, TableDataChangeDTO.class);
                if (Objects.isNull(tableDataChangeDTO)) {
                    throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
                }

                // 处理消息
                messageHandlerManager.handleMessage(tableDataChangeDTO);

                // 发送回调消息
                defaultProducer.sendMessage(tableDataChangeDTO.getCallbackTopic(),
                        tableDataChangeDTO.getMessageNo(), RocketDelayedLevel.DELAYED_1m, "表变更消息处理完成返回延迟消息");
            }
        } catch (Exception e) {
            log.error("consume error, 商品索引数据更新失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
